﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using PMSGSC.Common;
using DevExpress.XtraEditors;
using PMSGSC.DAL;
using PMSGSC.BLL;
using System.IO;
using DevExpress.XtraTab;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraEditors.Controls;
using DevExpress.XtraBars;
using DevExpress.XtraGrid.Columns;
using System.Diagnostics;
using DevExpress.XtraGrid;
using DevExpress.XtraGrid.Localization;
using System.Data.Linq;

namespace PMSGSC.App
{
    public partial class frmWorkOrderDeatails : DevExpress.XtraEditors.XtraForm
    {
        public frmWorkOrderDeatails(List<WorkOrder> listSource, frmMain objMain)
        {
            InitializeComponent();

            if (listSource == null)
                workOrderBindingSource.DataSource = WorkOrder_BLL.GetDataByEquipmentID(0, frmMain.ship.Ship_ID, false);
            else
                workOrderBindingSource.DataSource = listSource;

            statusJobBindingSource.DataSource = StatusJob_BLL.GetAll(frmMain.ship.Ship_ID);
            employeeBindingSource.DataSource = Employee_BLL.GetAll(frmMain.ship.Ship_ID);
            serviceCodeBindingSource.DataSource = ServiceCode_BLL.GetAll(frmMain.ship.Ship_ID);
            main = objMain;
        }
        WorkOrder WorkOrder;
        frmMain main;
        public void SelectAllWO()
        {
            foreach (WorkOrder j in workOrderBindingSource.Cast<WorkOrder>().ToList())
            {
                j.IsCheck = true;
            }
            repositoryItemCheckEdit1.ValueChecked = true;
        }

        public void DeSelectAllWO()
        {
            foreach (WorkOrder j in workOrderBindingSource.Cast<WorkOrder>().ToList())
            {
                j.IsCheck = false;
            }
            repositoryItemCheckEdit1.ValueChecked = false;
        }

        public List<WorkOrder> GetNumberOfWorkOrderBeforePrint()
        {
            List<WorkOrder> WorkOrderList = new List<WorkOrder>();
            foreach (WorkOrder j in workOrderBindingSource.Cast<WorkOrder>().ToList())
            {
                if (j.IsCheck.Value)
                    WorkOrderList.Add(j);
            }
            return WorkOrderList;
        }

        private void WorkOrderBindingSource_CurrentChanged(object sender, EventArgs e)
        {
            if (WorkOrder != null)
            {
                if (ucLoadEquipment1.isChanges)
                {
                    if (ucLoadEquipment1.lbid.Text != "")
                    {
                        WorkOrder.Equipment = BaseDAL.DB.Equipments.Single(c => c.Equipment_ID == int.Parse(ucLoadEquipment1.lbid.Text));
                        ucLoadEquipment1.isChanges = false;
                    }
                }
                if (ucRichEditControl1.isChange)
                {
                    WorkOrder.Detail = ucRichEditControl1.richEditControl1.Text;
                    ucRichEditControl1.isChange = false;
                }
                if (ucRichEditControl2.isChange)
                {
                    WorkOrder.JobDescription = ucRichEditControl2.richEditControl1.Text;
                    ucRichEditControl2.isChange = false;
                }
            }
            WorkOrder = workOrderBindingSource.Current as WorkOrder;
            if (WorkOrder != null)
            {
                ucRichEditControl2.richEditControl1.Text = WorkOrder.JobDescription;
                ucRichEditControl1.richEditControl1.Text = WorkOrder.Detail;
                if (WorkOrder.Equipment != null)
                {
                    ucLoadEquipment1.SetValue(WorkOrder.Equipment.CodeEquipment, WorkOrder.Equipment.NameEquipment, WorkOrder.Equipment_ID.ToString());
                }
                if (WorkOrder.Type == 3)
                    txtType.Text = "Round";
                else
                    txtType.Text = "";
            }
            LoadDataIntoTabPageWorkOrder();
        }

        private DateTime NextDue(string Frequency, DateTime LastDone, string TimeUnit)
        {

            int Number = int.Parse(Frequency);
            DateTime dt = LastDone;
            switch (TimeUnit)
            {
                case "Day(s)":
                    dt = dt.AddDays(Number);
                    break;
                case "Week(s)":
                    int NumberDay = Number * 7;
                    dt = dt.AddDays(NumberDay);
                    break;
                case "Month(s)":
                    dt = dt.AddMonths(Number);
                    break;
            }
            return dt;
        }

        private int Deadline(WorkOrder j)
        {
            for (int i = 0; i < nextDueTempList.Count; i++)
            {
                if (j.WorkOrder_ID == nextDueTempList[i].Id)
                    return i;
            }
            return -1;
        }

        public void SaveWorkOrders()
        {
            SetValueBeforeUpdate();
            if (isWorkOrderChanged)
            {
                foreach (WorkOrder j in workOrderBindingSource.Cast<WorkOrder>().ToList())
                {
                    int index = Deadline(j);
                    j.IsCheck = false;
                    if (index != -1)
                    {
                        frmRescheduleLog reschedule = new frmRescheduleLog();
                        reschedule.Title = j.Title;
                        reschedule.res.WorkOrder_ID = j.WorkOrder_ID;
                        reschedule.res.Employee_ID = j.RespDescipline_ID;
                        reschedule.res.Date = DateTime.Now.Date;

                        if (nextDueTempList[index].OldNextDue.Date == new DateTime(0001, 01, 01))
                            reschedule.res.FromDate = null;
                        else
                            reschedule.res.FromDate = nextDueTempList[index].OldNextDue;

                        reschedule.res.ToDate = nextDueTempList[index].NewNextDue;
                        reschedule.ShowDialog();

                        if (reschedule.Option)
                        {
                            WorkOrder_BLL.Update(j);
                            nextDueTempList.RemoveAt(index);
                        }
                    }
                    else
                    {
                        WorkOrder_BLL.Update(j);
                    }
                }
                if (nextDueTempList.Count == 0)
                {
                    isWorkOrderChanged = false;
                }
            }
        }

        private void SetValueBeforeUpdate()
        {
            WorkOrder j1 = workOrderBindingSource.Current as WorkOrder;
            j1.Title = titleTextEdit.Text;
            j1.NextDue = nextDueDateEdit.DateTime.Date;
            j1.LastDone = lastDoneDateEdit.DateTime.Date;

            if (ucLoadEquipment1.isChanges)
            {
                j1.Equipment = BaseDAL.DB.Equipments.Single(c => c.Equipment_ID == int.Parse(ucLoadEquipment1.lbid.Text));
                ucLoadEquipment1.isChanges = false;
            }
            if (ucRichEditControl1.isChange)
            {
                j1.Detail = ucRichEditControl1.richEditControl1.Text;
                ucRichEditControl1.isChange = false;
            }
            if (ucRichEditControl2.isChange)
            {
                j1.JobDescription = ucRichEditControl2.richEditControl1.Text;
                ucRichEditControl2.isChange = false;
            }
            if (alarmDaybeforeTextEdit1.ContainsFocus && alarmDaybeforeTextEdit1.Text != "")
            {
                j1.AlarmDaybefore = int.Parse(alarmDaybeforeTextEdit1.Text);
            }
            if (effectMemoEdit.ContainsFocus)
            {
                j1.Effect = effectMemoEdit.Text;
            }
            if (causeMemoEdit.ContainsFocus)
            {
                j1.Cause = causeMemoEdit.Text;
            }
            if (actionTakenMemoEdit.ContainsFocus)
            {
                j1.ActionTaken = actionTakenMemoEdit.Text;
            }
            if (overdueReasonMemoEdit.ContainsFocus)
            {
                j1.OverdueReason = overdueReasonMemoEdit.Text;
            }
        }

        private void LoadDataIntoTabPageWorkOrder()
        {
            XtraTabPage tabpage = xtraTabControl1.SelectedTabPage;
            WorkOrder j = workOrderBindingSource.Current as WorkOrder;
            if (j != null)
            {
                switch (tabpage.Name)
                {
                    case "RP":
                        partWorkOrderBindingSource.DataSource = PartWorkOrder_BLL.GetDataByWorkOrderID(j.WorkOrder_ID, true);
                        break;
                    case "AJ":
                        attachmentWorkOrderBindingSource.DataSource = AttachmentWorkOrder_BLL.GetDataByworkOrderID(j.WorkOrder_ID, isChangedAJ);
                        isChangedAJ = false;
                        break;
                    case "IncludeJob":
                        if (j.Type  == 3)
                            roundJobBindingSource.DataSource = RoundJob_BLL.GetDataByRoundID(j.Round_ID.Value, false);
                        break;
                }
            }
            else
            {
                switch (tabpage.Name)
                {
                    case "RP":
                        partWorkOrderBindingSource.DataSource = null;
                        break;
                    case "AJ":
                        attachmentWorkOrderBindingSource.DataSource = null;
                        break;
                    case "IncludeJob":
                        roundJobBindingSource.DataSource = null;
                        break;
                }

            }
        }

        #region Part  in WorkOrder

        // Khai báo trạng thái mặc định 
        private Status statusPartWorkOrder = Status.Update;
        // Tạo một đối tượng lưu trữ các thông tin trên View ==> truyền xuống các layer bên dưới
        private PartWorkOrder wPart;
        //Hiển thị số thứ tự của gridview
        private void gridViewPJ_CustomDrawRowIndicator(object sender, DevExpress.XtraGrid.Views.Grid.RowIndicatorCustomDrawEventArgs e)
        {
            if (e.RowHandle >= 0)
            {
                e.Info.DisplayText = (e.RowHandle + 1).ToString();
            }
        }
        // Sự kiện cập nhật dữ liệu xuống database
        private void gridViewPJ_RowUpdated(object sender, DevExpress.XtraGrid.Views.Base.RowObjectEventArgs e)
        {
            SavePartWorkOrderToDatabase();
        }
        private void txtQuantity_KeyPress(object sender, KeyPressEventArgs e)
        {
            OnlyInputNumberic(e);
        }

        private static void OnlyInputNumberic(KeyPressEventArgs e)
        {
            const char Delete = (char)8;
            e.Handled = !Char.IsDigit(e.KeyChar) && e.KeyChar != Delete;
        }
        private void DeletePartWorkOrder(NavigatorButtonClickEventArgs e)
        {
            wPart = partWorkOrderBindingSource.Current as PartWorkOrder;
            if (XtraMessageBox.Show("Are you sure you want to delete a Part?", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
            {
                bool result = PartWorkOrder_BLL.Delete(wPart);
                if (!result)
                {
                    XtraMessageBox.Show("Can't Delete", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
                partWorkOrderBindingSource.DataSource = PartWorkOrder_BLL.GetDataByWorkOrderID(WorkOrder.WorkOrder_ID, true);
            }
            e.Handled = true;
            
        }

        private bool TestBeforeAddPartWorkOrder()
        {
            if (WorkOrder != null)
            {
                return true;
            }
            return false;
        }

        private void SavePartWorkOrderToDatabase()
        {
            if (TestBeforeAddPartWorkOrder())
            {
                wPart = partWorkOrderBindingSource.Current as PartWorkOrder;
                if (statusPartWorkOrder == Status.Update)
                {
                    if (XtraMessageBox.Show("Do you want to save changes?", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
                    {
                        bool result = PartWorkOrder_BLL.Update(wPart);
                        if (!result)
                        {
                            XtraMessageBox.Show("Update Unsuccess!", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        }
                    }
                    partWorkOrderBindingSource.DataSource = PartWorkOrder_BLL.GetDataByWorkOrderID(WorkOrder.WorkOrder_ID, true);
                }
                if (statusPartWorkOrder == Status.New)
                {
                    bool result = PartWorkOrder_BLL.Insert(wPart);
                    if (!result)
                    {
                        XtraMessageBox.Show("Insert Unsuccess!", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
                    statusPartWorkOrder = Status.Update;
                }
            }
        }
        // Sự kiện nhân phím delete sảy ra
        private void gridViewPJ_KeyDown(object sender, KeyEventArgs e)
        {
            if (TestBeforeAddPartWorkOrder())
            {
                wPart = partWorkOrderBindingSource.Current as PartWorkOrder;
                if (e.KeyCode == Keys.Delete)
                {
                    if (XtraMessageBox.Show("Are you sure you want to delete a Part?", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
                    {
                        bool result = PartWorkOrder_BLL.Delete(wPart);
                        if (!result)
                        {
                            XtraMessageBox.Show("Can't Delete", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        }
                        partWorkOrderBindingSource.DataSource = PartWorkOrder_BLL.GetDataByWorkOrderID(WorkOrder.WorkOrder_ID, true);
                    }
                    e.Handled = true;
                }
            }
        }

        // Khởi tạo giá trị mặc định của ô cần ràng buộc
        private void gridViewPJ_InitNewRow(object sender, DevExpress.XtraGrid.Views.Grid.InitNewRowEventArgs e)
        {
            statusPartWorkOrder = Status.New;
            GridView view = (GridView)sender;

            GridColumn Quantity = view.Columns["Quantity"];
            view.SetRowCellValue(e.RowHandle, Quantity, 0);
        }
        // Kiểm tra ràng buộc của dữ liệu người dùng nhập vào
        private void gridViewPJ_ValidateRow(object sender, DevExpress.XtraGrid.Views.Base.ValidateRowEventArgs e)
        {
            
            if (null != WorkOrder)
            {
                GridView view = (GridView)sender;
                GridColumn PartCode = view.Columns["PartCode"];
                if (null == view.GetRowCellValue(e.RowHandle, PartCode))
                {
                    e.Valid = false;
                    view.FocusedColumn = PartCode;
                    e.ErrorText = "Please enter the Part ";
                    view.SetColumnError(PartCode, "Part cannot be empty");
                    return;
                }
                if (null == PartInEquipment_BLL.GetDataByNumber(view.GetRowCellDisplayText(view.FocusedRowHandle, PartCode)))
                {
                    e.Valid = false;
                    view.FocusedColumn = PartCode;
                    e.ErrorText = "Please enter the Part ";
                    view.SetColumnError(PartCode, "Part hasn't existed");
                    return;
                }
                if (PartWorkOrder_BLL.isExits(wPart) && statusPartWorkOrder != Status.Update)
                {
                    e.Valid = false;
                    view.FocusedColumn = PartCode;
                    e.ErrorText = "Part has existed.";
                    view.SetColumnError(PartCode, "Part has existed");
                    return;
                }
            }
        }
        // Thông báo lỗi nếu dữ liệu nhập vào không đúng
        private void gridViewPJ_InvalidRowException(object sender, DevExpress.XtraGrid.Views.Base.InvalidRowExceptionEventArgs e)
        {
            if (e.RowHandle == GridControl.NewItemRowHandle)
            {
                e.WindowCaption = "Input Error";
            }
            else
            {
                e.ExceptionMode = DevExpress.XtraEditors.Controls.ExceptionMode.NoAction;
                DialogResult dr = XtraMessageBox.Show(gridControl1.LookAndFeel, this, e.ErrorText + GridLocalizer.Active.GetLocalizedString(GridStringId.ColumnViewExceptionMessage), e.WindowCaption, MessageBoxButtons.YesNo, MessageBoxIcon.Error);
                if (dr == DialogResult.No)
                {
                    e.ExceptionMode = DevExpress.XtraEditors.Controls.ExceptionMode.Ignore;
                    partWorkOrderBindingSource.DataSource = PartWorkOrder_BLL.GetDataByWorkOrderID(WorkOrder.WorkOrder_ID, false);
                    statusPartWorkOrder = Status.Update;
                }
            }

        }
        private bool flag = false;
        // Đặt lại trạng thái update 
        private void gridViewPJ_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            if (e.RowHandle != GridControl.NewItemRowHandle)
            {
                statusPartWorkOrder = Status.Update;
            }

            GridView view = gridControl3.FocusedView as GridView;
            if (e.Column.FieldName == "PartCode" && flag == false)
            {
                flag = true;
                if (e.Value != null && view.FocusedRowHandle == GridControl.NewItemRowHandle)
                {
                    PartsInEquipment part;
                    part = PartInEquipment_BLL.GetDataByNumber(view.GetRowCellDisplayText(view.FocusedRowHandle, e.Column));

                    if (part != null)
                    {
                        if (view.IsNewItemRow(view.FocusedRowHandle) && view.GetRow(view.FocusedRowHandle) == null)
                        {
                            view.AddNewRow();
                        }

                        view.SetRowCellValue(view.FocusedRowHandle, colPartCode, part.PartCode);
                        view.SetRowCellValue(view.FocusedRowHandle, colPartName, part.PartName);
                        view.SetRowCellValue(view.FocusedRowHandle, colQuantity, 0);

                        wPart.PartsInEquipment = part;
                    }
                    else
                    {
                        view.SetColumnError(colPartCode, "Equipment cannot be empty");
                        view.SetRowCellValue(view.FocusedRowHandle, colPartCode, "");
                        view.SetRowCellValue(view.FocusedRowHandle, colPartName, "");
                        wPart.PartsInEquipment = null;
                    }
                    flag = false;
                }

            }
        }

        #endregion


        #region Attachment WorkOrder

        // Khai báo trạng thái mặc định 
        private Status statusAttachmentWorkOrder = Status.Update;
        // Tạo một đối tượng lưu trữ các thông tin trên View ==> truyền xuống các layer bên dưới
        private AttachmentWorkOrder attachmentWorkOrder = new AttachmentWorkOrder();
        //Hiển thị số thứ tự của gridview

        private void gridViewAJ_CustomDrawRowIndicator(object sender, DevExpress.XtraGrid.Views.Grid.RowIndicatorCustomDrawEventArgs e)
        {
            if (e.RowHandle >= 0)
            {
                e.Info.DisplayText = (e.RowHandle + 1).ToString();
            }
        }

        private bool isChangedAJ;
        private void attachmentsWorkOrderBindingSource_CurrentItemChanged(object sender, EventArgs e)
        {
            isChangedAJ = true;
        }

        private void attachmentsWorkOrderBindingSource_CurrentChanged(object sender, EventArgs e)
        {
            attachmentWorkOrder = attachmentWorkOrderBindingSource.Current as AttachmentWorkOrder;
        }

        private void btnOpenFileWorkOrder_ButtonClick(object sender, ButtonPressedEventArgs e)
        {
            try
            {
                OpenDocumentAJ();
            }
            catch { }
        }

        private void btnUploadFileAJ_ButtonClick(object sender, ButtonPressedEventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Title = "Select one file upload";
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                string fileName = openFileDialog.InitialDirectory + openFileDialog.FileName;
                FileInfo fileInfo = new FileInfo(fileName);
                long sizeFile = fileInfo.Length / 1000;
                if (sizeFile <= 3000)
                {

                    string extension = Path.GetExtension(fileName);
                    attachmentWorkOrder.Extension = extension;
                    byte[] fileByteArray = StreamFile(fileName);
                    // Converts it to Binary
                    // it can be done inside the method as well
                    Binary fileBinary = new Binary(fileByteArray);
                    attachmentWorkOrder.ContentFile = fileBinary;
                    GridColumn AttachExtension = gridView13.Columns["Extentsion"];
                    extension = extension.ToUpper();
                    gridView13.SetRowCellValue(gridView13.FocusedRowHandle, AttachExtension, extension);
                }
                else
                {
                    XtraMessageBox.Show("The size file  must be less than 3M ", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
        }

        private byte[] StreamFile(string fileName)
        {
            // Open file
            FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);

            // ByteArray
            byte[] ImageData = new byte[fs.Length];

            // Read block of bytes
            fs.Read(ImageData, 0, System.Convert.ToInt32(fs.Length));

            // Close it
            fs.Close();

            // Return the byte data
            return ImageData;
        }

        // Sự kiện cập nhật dữ liệu xuống database
        private void gridViewAJ_RowUpdated(object sender, DevExpress.XtraGrid.Views.Base.RowObjectEventArgs e)
        {
              SaveAttachmentWorkOrderToDatabase();
        }

        private static void LoadSkinToForm()
        {
            DevExpress.Skins.SkinManager.EnableFormSkins();
            DevExpress.UserSkins.BonusSkins.Register();
            DevExpress.UserSkins.OfficeSkins.Register();
            DevExpress.LookAndFeel.DefaultLookAndFeel obj = new DevExpress.LookAndFeel.DefaultLookAndFeel();
            try
            {
                LookAndFeelSettings.Load("LookAndFeelSettings.dat");
            }
            catch
            {
                obj.LookAndFeel.SetSkinStyle("Blue");
            }
        }
        private void SaveAttachmentWorkOrderToDatabase()
        {
            if (TestBeforeAddPartWorkOrder())
            {

                frmProcessBar pb = new frmProcessBar();
                System.Threading.Thread thread = new System.Threading.Thread(new System.Threading.ThreadStart(() =>
                {
                    LoadSkinToForm();
                    pb.ShowDialog();
                }
                ));

                if (statusAttachmentWorkOrder == Status.Update)
                {
                    if (XtraMessageBox.Show("Do you want to save changes?", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
                    {
                        thread.Start();
                        bool result = AttachmentWorkOrder_BLL.Update(attachmentWorkOrder);
                        if (pb.InvokeRequired)
                            pb.BeginInvoke(new Action(() => pb.Close()));

                        if (!result)
                            XtraMessageBox.Show("Update Unsuccess !", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        else
                            XtraMessageBox.Show("Update Success !", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);

                        attachmentWorkOrderBindingSource.DataSource = AttachmentWorkOrder_BLL.GetDataByworkOrderID(WorkOrder.WorkOrder_ID, isChangedAJ);
                        isChangedAJ = false;
                    }
                }

                if (statusAttachmentWorkOrder == Status.New)
                {
                    thread.Start();
                    attachmentWorkOrder.WorkOrder_ID = WorkOrder.WorkOrder_ID;
                    bool result = AttachmentWorkOrder_BLL.Insert(attachmentWorkOrder);

                    if (pb.InvokeRequired)
                        pb.BeginInvoke(new Action(() => pb.Close()));

                    if (!result)
                    {
                        XtraMessageBox.Show("Insert Unsuccess!", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
                    statusAttachmentWorkOrder = Status.Update;
                }

              
            }
        }
        private void DeleteAttachmentWorkOrder(NavigatorButtonClickEventArgs e)
        {
            DeleteAttachmentWorkOrderFinal();
            e.Handled = true;
        }

        private void DeleteAttachmentWorkOrderFinal()
        {
            if (XtraMessageBox.Show("Are you sure you want to delete a Attachment?", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
            {
                bool result = AttachmentWorkOrder_BLL.Delete(attachmentWorkOrder);
                if (!result)
                {
                    XtraMessageBox.Show("Can't Delete", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
                attachmentWorkOrderBindingSource.DataSource = AttachmentWorkOrder_BLL.GetDataByworkOrderID(WorkOrder.WorkOrder_ID, isChangedAJ);
                isChangedAJ = false;
            }
        }
        // Sự kiện nhân phím delete sảy ra
        private void gridViewAJ_KeyDown(object sender, KeyEventArgs e)
        {
            if (TestBeforeAddPartWorkOrder())
            {
                if (e.KeyCode == Keys.Delete)
                {
                    DeleteAttachmentWorkOrderFinal();
                }
            }
        }
        // Khởi tạo giá trị mặc định của ô cần ràng buộc
        private void gridViewAJ_InitNewRow(object sender, DevExpress.XtraGrid.Views.Grid.InitNewRowEventArgs e)
        {
            if (TestBeforeAddPartWorkOrder())
            {
                statusAttachmentWorkOrder = Status.New;
            }
        }
        // Kiểm tra ràng buộc của dữ liệu người dùng nhập vào
        private void gridViewAJ_ValidateRow(object sender, DevExpress.XtraGrid.Views.Base.ValidateRowEventArgs e)
        {
            if (null != WorkOrder)
            {
                GridView view = (GridView)sender;
                GridColumn AttachName = view.Columns["Name"];
                GridColumn AttachCode = view.Columns["Code"];
                GridColumn AttachContent = view.Columns["ContentFile"];

                if (null == view.GetRowCellValue(e.RowHandle, AttachName))
                {
                    e.Valid = false;
                    view.FocusedColumn = AttachName;
                    e.ErrorText = "Please enter the Attachment Name. ";
                    view.SetColumnError(AttachName, "Attachment Name is not empty");
                    return;
                }
                if (null == view.GetRowCellValue(e.RowHandle, AttachCode))
                {
                    e.Valid = false;
                    view.FocusedColumn = AttachCode;
                    e.ErrorText = "Please enter the Attachment Code. ";
                    view.SetColumnError(AttachCode, "Attachment Code is not empty");
                    return;
                }
                if (null == view.GetRowCellValue(e.RowHandle, AttachContent))
                {
                    e.Valid = false;
                    e.ErrorText = "Please upload one file into table ";
                    return;
                }
                attachmentWorkOrder = attachmentWorkOrderBindingSource.Current as AttachmentWorkOrder;
                attachmentWorkOrder.WorkOrder_ID = WorkOrder.WorkOrder_ID;
                if (AttachmentWorkOrder_BLL.IsExits(attachmentWorkOrder))
                {
                    e.Valid = false;
                    view.FocusedColumn = AttachCode;
                    e.ErrorText = "Attachment Code is exits. ";
                    view.SetColumnError(AttachCode, "Attachment Code is exits");
                    return;
                }
            }
        }

        // Thông báo lỗi nếu dữ liệu nhập vào không đúng
        private void gridViewAJ_InvalidRowException(object sender, DevExpress.XtraGrid.Views.Base.InvalidRowExceptionEventArgs e)
        {

            if (e.RowHandle == GridControl.NewItemRowHandle)
            {
                e.WindowCaption = "Input Error";
            }
            else
            {
                e.ExceptionMode = DevExpress.XtraEditors.Controls.ExceptionMode.NoAction;
                DialogResult dr = XtraMessageBox.Show(gridControl1.LookAndFeel, this, e.ErrorText + GridLocalizer.Active.GetLocalizedString(GridStringId.ColumnViewExceptionMessage), e.WindowCaption, MessageBoxButtons.YesNo, MessageBoxIcon.Error);
                if (dr == DialogResult.No)
                {
                    e.ExceptionMode = DevExpress.XtraEditors.Controls.ExceptionMode.Ignore;
                    attachmentWorkOrderBindingSource.DataSource = AttachmentWorkOrder_BLL.GetDataByworkOrderID(WorkOrder.WorkOrder_ID, isChangedAJ);
                    isChangedAJ = false;
                }
            }
        }

        // Đặt lại trạng thái update 
        private void gridViewAJ_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            if (e.RowHandle != GridControl.NewItemRowHandle)
            {
                statusAttachmentWorkOrder = Status.Update;
            }
        }
        public bool ByteArrayToFile(string fileName, byte[] byteArray)
        {
            try
            {
                // Open file for reading
                System.IO.FileStream fileStream = new System.IO.FileStream
                    (fileName, System.IO.FileMode.Create, System.IO.FileAccess.Write);
                // Writes a block of bytes
                fileStream.Write(byteArray, 0, byteArray.Length);

                // Close file stream
                fileStream.Close();

                return true;
            }
            catch (Exception exp)
            {
                Console.WriteLine(exp.ToString());
            }
            return false;
        }

        private void OpenDocumentAJ()
        {
            if (gridView13.FocusedRowHandle != GridControl.NewItemRowHandle)
            {
                string Address = Application.StartupPath + "\\Attachment\\";
                Directory.CreateDirectory(Address);
                AttachmentWorkOrder attach = AttachmentWorkOrder_BLL.GetDataById(attachmentWorkOrder.Attachment_ID);

                if (null != attach)
                {
                    string fileName = attach.Name + attach.Extension;
                    Address += fileName;
                    if (ByteArrayToFile(Address, attach.ContentFile.ToArray()))
                    {
                        try
                        {
                            Process.Start(Address);
                        }
                        catch
                        {
                            XtraMessageBox.Show("Can't open file", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        }
                    }
                }
            }
        }

        #endregion

        public bool isWorkOrderChanged { get; set; }
        private void WorkOrderBindingSource_CurrentItemChanged(object sender, EventArgs e)
        {
            isWorkOrderChanged = true;
        }

        public bool isChangedA { get; set; }

        private void xtraTabControl1_SelectedPageChanged(object sender, TabPageChangedEventArgs e)
        {
            LoadDataIntoTabPageWorkOrder();
        }

        List<NextDueTemp> nextDueTempList = new List<NextDueTemp>();
        private int Delete(int id)
        {
            for (int i = 0; i < nextDueTempList.Count; i++)
            {
                if (nextDueTempList[i].Id == id)
                    return i;
            }
            return -1;
        }
        private void nextDueDateEdit_EditValueChanged(object sender, EventArgs e)
        {
            if (nextDueDateEdit.ContainsFocus)
            {
                WorkOrder j = workOrderBindingSource.Current as WorkOrder;
                NextDueTemp ndTemp = new NextDueTemp();
                int result = Delete(j.WorkOrder_ID);
                if (result != -1)
                {
                    nextDueTempList[result].NewNextDue = nextDueDateEdit.DateTime;
                }
                else
                {
                    ndTemp.Id = j.WorkOrder_ID;
                    if (j.NextDue != null)
                    {
                        ndTemp.OldNextDue = j.NextDue.Value;
                    }
                    ndTemp.NewNextDue = nextDueDateEdit.DateTime;
                    nextDueTempList.Add(ndTemp);
                }
            }
        }

        private void gridView1_CustomDrawRowIndicator(object sender, RowIndicatorCustomDrawEventArgs e)
        {
            if (e.RowHandle >= 0)
            {
                e.Info.DisplayText = (e.RowHandle + 1).ToString();
            }
        }

        private void gridView1_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            if (e.Column.Name != "colIsCheck")
                return;
        }

        private void repositoryItemCheckEdit1_CheckedChanged(object sender, EventArgs e)
        {
            WorkOrder.IsCheck = bool.Parse(repositoryItemCheckEdit1.ValueChecked.ToString());
        }

        private void rescheduleLogToolStripMenuItem_Click(object sender, EventArgs e)
        {
            frmShowRescheduleLog reschedule = new frmShowRescheduleLog();
            reschedule.MdiParent = main;
            reschedule.Show();
        }

        private void employee_IDGridLookUpEdit_EditValueChanging(object sender, ChangingEventArgs e)
        {
            if (e.NewValue == null)
                ((WorkOrder)gridView1.GetFocusedRow()).Employee = null;
            else
                ((WorkOrder)gridView1.GetFocusedRow()).Employee = BaseDAL.DB.Employees.Single(c => c.Employee_ID == (int)e.NewValue);
        }

        private void statusWorkOrder_IDLookUpEdit_EditValueChanging(object sender, ChangingEventArgs e)
        {
            if (e.NewValue == null)
                ((WorkOrder)gridView1.GetFocusedRow()).StatusJob = null;
            else
                ((WorkOrder)gridView1.GetFocusedRow()).StatusJob = BaseDAL.DB.StatusJobs.Single(c => c.StatusJob_ID == (int)e.NewValue);
        }

        private void sC_IDGridLookUpEdit_EditValueChanging(object sender, ChangingEventArgs e)
        {
            if (e.NewValue == null)
                ((WorkOrder)gridView1.GetFocusedRow()).ServiceCode = null;
            else
                ((WorkOrder)gridView1.GetFocusedRow()).ServiceCode = BaseDAL.DB.ServiceCodes.Single(c => c.SC_ID == (int)e.NewValue);
        }

        private void btnSaveAll_ItemClick(object sender, ItemClickEventArgs e)
        {
            SaveWorkOrders();
        }

        private void btnDelete_ItemClick(object sender, ItemClickEventArgs e)
        {
            if (WorkOrder != null)
            {
                if (!WorkOrder_BLL.TestBeforeDelete(WorkOrder))
                    XtraMessageBox.Show("Can't Delete", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                else
                {
                    WorkOrder_BLL.Delete(WorkOrder);
                }
                if(ucLoadEquipment1.lbid.Text != "")
                {
                    workOrderBindingSource.DataSource = WorkOrder_BLL.GetDataByEquipmentID(int.Parse(ucLoadEquipment1.lbid.Text), frmMain.ship.Ship_ID, true);
                }
            }
        }

        private void btnRefresh_ItemClick(object sender, ItemClickEventArgs e)
        {
            XtraMessageBox.Show("This function building", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        private void btnPrint_ItemClick(object sender, ItemClickEventArgs e)
        {
            List<WorkOrder> workOrder = GetNumberOfWorkOrderBeforePrint();
            if (workOrder.Count > 0)
            {
                frmReportWorkOrder reportWorkOrder = new frmReportWorkOrder(workOrder);
                reportWorkOrder.MdiParent = main;
                reportWorkOrder.Show();
            }
        }
       
        private void freodicFrequencyTextEdit_KeyPress(object sender, KeyPressEventArgs e)
        {
            OnlyInputNumberic(e);
        }

        private void gridControl3_EmbeddedNavigator_ButtonClick(object sender, NavigatorButtonClickEventArgs e)
        {
            if (TestBeforeAddPartWorkOrder())
            {
                switch (e.Button.ButtonType)
                {
                    case NavigatorButtonType.Remove:
                        DeletePartWorkOrder(e);
                        break;
                }
            }
        }

        private void gridControl17_EmbeddedNavigator_ButtonClick(object sender, NavigatorButtonClickEventArgs e)
        {
            if (TestBeforeAddPartWorkOrder())
            {
                switch (e.Button.ButtonType)
                {
                    case NavigatorButtonType.Remove:
                        if (TestBeforeAddPartWorkOrder())
                        {
                            DeleteAttachmentWorkOrder(e);
                        }
                        break;
                }
            }
        }

        private void repositoryItemGridLookUpEdit5_EditValueChanging(object sender, ChangingEventArgs e)
        {
            if (e.NewValue == null)
                ((PartWorkOrder)gridView15.GetFocusedRow()).PartsInEquipment = null;
            else
                ((PartWorkOrder)gridView15.GetFocusedRow()).PartsInEquipment = BaseDAL.DB.PartsInEquipments.Single(n => n.Parts_ID == (int)e.NewValue);
        }

        private void repositoryItemGridLookUpEdit6_EditValueChanging(object sender, ChangingEventArgs e)
        {
            if (e.NewValue == null)
                ((PartWorkOrder)gridView15.GetFocusedRow()).PartsInEquipment = null;
            else
                ((PartWorkOrder)gridView15.GetFocusedRow()).PartsInEquipment = BaseDAL.DB.PartsInEquipments.Single(n => n.Parts_ID == (int)e.NewValue);
        }

        private void gridView4_ShowingEditor(object sender, CancelEventArgs e)
        {
            e.Cancel = true;
        }

        private void gridView1_ShowingEditor(object sender, CancelEventArgs e)
        {
            GridView view = sender as GridView;
            GridColumn IsCheckCol = view.Columns["IsCheck"];
            if (!view.IsNewItemRow(view.FocusedRowHandle) && view.FocusedColumn != IsCheckCol)
                e.Cancel = true;
        }

        private void gridView4_CustomDrawRowIndicator(object sender, RowIndicatorCustomDrawEventArgs e)
        {
            if (e.RowHandle >= 0)
            {
                e.Info.DisplayText = (e.RowHandle + 1).ToString();
            }
        }

        private void reportWorkToolStripMenuItem_Click(object sender, EventArgs e)
        {
            frmCloseJobDetail closeJobDetail = new frmCloseJobDetail(WorkOrder);
            closeJobDetail.MdiParent = main;
            closeJobDetail.Show();
        }

        private void btnLoadPart_ButtonClick(object sender, ButtonPressedEventArgs e)
        {
            frmGridPart gridPart = new frmGridPart();
            gridPart.ShowDialog();

            GridView view = gridView15 as GridView;

            if (view.IsNewItemRow(view.FocusedRowHandle) && view.GetRow(view.FocusedRowHandle) == null)
            {
                view.AddNewRow();
            }
            if (gridPart.PartsInEquipment != null)
            {
                view.SetRowCellValue(view.FocusedRowHandle, colPartCode, gridPart.PartsInEquipment.PartCode);
                view.SetRowCellValue(view.FocusedRowHandle, colPartName, gridPart.PartsInEquipment.PartName);
                view.SetRowCellValue(view.FocusedRowHandle, colQuantity, 0);

                wPart.PartsInEquipment = gridPart.PartsInEquipment;
            }
        }

        private void partWorkOrderBindingSource_CurrentChanged(object sender, EventArgs e)
        {
            wPart = partWorkOrderBindingSource.Current as PartWorkOrder;
            if (wPart != null)
                wPart.WorkOrder = WorkOrder;
        }

        private void gridView15_ShowingEditor(object sender, CancelEventArgs e)
        {
            GridView view = sender as GridView;
            if (!view.IsNewItemRow(view.FocusedRowHandle) && view.FocusedColumn != colQuantity)
                e.Cancel = true;
        }

    }
}